<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      @submit.native.prevent
      :inline="true"
      v-show="showSearch"
      label-width="40px"
    >
      <el-form-item label="名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="5" style="padding-right: 0 !important">
        <left-tree
          ref="leftRef"
          @getParentId="getParentIdFunc"
          @cateChange="cateChange"
        />
      </el-col>
      <el-col :span="19" style="padding-left: 10 !important">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['technology:technologyWorkingProduct:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['technology:technologyWorkingProduct:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['technology:technologyWorkingProduct:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-download"
              size="mini"
              :loading="btnLoading"
              @click="handleExport"
              v-hasPermi="['technology:technologyWorkingProduct:export']"
              >导出</el-button
            >
          </el-col>
          <!-- <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar> -->
        </el-row>

        <el-table
          border
          :cell-style="{ padding: this.tablePadding }"
          v-loading="loading"
          :data="productList"
          highlight-current-row
          height="250"
          @selection-change="handleSelectionChange"
          @row-click="getInfo"
        >
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column label="产品名称" align="center" prop="productName" />
          <el-table-column
            label="产品分类"
            align="center"
            prop="productCategoryName"
          />
          <el-table-column label="加工任务" align="center" prop="workingName" />
          <el-table-column label="描述" align="center" prop="description" />

          <el-table-column label="产品图像" align="center" prop="imageUrl">
            <template slot-scope="scope">
              <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy" />
          <el-table-column label="创建时间" align="center" prop="createTime" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['technology:technologyWorkingProduct:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['technology:technologyWorkingProduct:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <el-row style="padding: 20px 0">
          <el-tabs>
            <el-tab-pane label="产品参数列表">
              <tab-details ref="detailsRef" />
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-col>
    </el-row>

    <!-- 添加或修改工艺管理成形产品对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        layout="inline"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="产品分类" prop="productCategoryId">
          <div style="width: 540px">
            <treeselect
              v-model="form.productCategoryId"
              :options="categoryList"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择产品分类"
            />
          </div>
        </el-form-item>
        <el-form-item label="加工任务" prop="workingId">
          <div class="input-width">
            <el-select
              v-model="form.workingId"
              placeholder="请输入加工任务"
              clearable
            >
              <el-option
                v-for="item in workingOptions"
                :key="item.workingId"
                :label="item.workingName"
                :value="item.workingId"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>

        <div></div>
        <el-form-item label="图像" prop="imageUrl">
          <!-- <el-input v-model="form.imageUrl" placeholder="请输入图像" /> -->
          <image-upload :value="form.imageUrl" @setValue="setImageUrl" />
        </el-form-item>
        <performance ref="performanceRef" titleLeft="性能参数" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="btnLoading"
          v-funThrottle="[submitForm]"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  listCategory,
  verifyProductName,
} from "@/api/technology/product";
import { getTechnologyWorkingList } from "@/api/technology/working";
import LeftTree from "./components/Left.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from "@/components/ImageUpload";
import Performance from "./components/Performance.vue";
import TabDetails from "./components/Details.vue";
export default {
  name: "Product",
  components: { LeftTree, Treeselect, ImageUpload, Performance, TabDetails },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工艺管理成形产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      btnLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productCategoryId: null,
      },
      // 表单参数
      form: {},
      workingOptions: [],
      categoryList: [],
      selectNames: [],
      // 表单校验
      rules: {
        workingId: [
          { required: true, message: "加工任务不能为空", trigger: "blur" },
        ],
        productCategoryId: [
          { required: true, message: "产品分类不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "建立人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "建立时间不能为空", trigger: "blur" },
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    // 获取任务下拉数据
    getTechnologyWorkingList({ status: 1 }).then((res) => {
      this.workingOptions = res.data;
    });
  },
  methods: {
    getInfo(row) {
      this.$refs.detailsRef.getInfo(row.productId);
    },
    setImageUrl(url) {
      this.form.imageUrl = url;
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.productCategoryId,
        label: node.productCategoryName,
        children: node.children,
      };
    },
    getParentIdFunc(len, id) {
      if (len > 0) {
        this.queryParams.productCategoryId = id;
        this.handleQuery();
      } else {
        this.loading = false;
      }
    },
    cateChange() {
      this.getCategoryList();
    },
    getCategoryList() {
      listCategory().then((response) => {
        this.categoryList = response.data;
      });
    },
    /** 查询工艺管理成形产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then((response) => {
        this.productList = response.rows;
        // if (this.productList.length > 0) {
        //   this.getInfo(this.productList[0]);
        // } else {
        this.$refs.detailsRef.tableData = [];
        // }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        workingId: null,
        productCategoryId: null,
        productCode: null,
        productName: null,
        description: null,
        imageUrl: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.selectNames = selection.map((item) => item.productName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加成形产品";
      this.form.productCategoryId = this.queryParams.productCategoryId;
      this.$nextTick(() => {
        this.$refs.performanceRef.setSelectItems = [];
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids;
      getProduct(productId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改成形产品";
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          this.$refs.performanceRef.setTable(this.form.technologyWorkingParams);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let arr = this.$refs.performanceRef.setSelectItems;
          this.form.technologyWorkingParams = arr;
          this.testName();
        }
      });
    },
    submitData() {
      this.btnLoading = true;
      if (this.form.productId != null) {
        updateProduct(this.form)
          .then((response) => {
            this.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            this.btnLoading = false;
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        addProduct(this.form)
          .then((response) => {
            this.msgSuccess("新增成功");
            this.open = false;
            // this.getList();
            this.btnLoading = false;
            // 设置新增数据时选中的节点，重显到tree上
            this.$refs.leftRef.setNodeId(this.form.productCategoryId);
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    // 添加/编辑验证名称重复
    testName() {
      verifyProductName({
        productName: this.form.productName,
        workingId: this.form.workingId,
      }).then((res) => {
        if (res.data == 0) {
          let _this = this;
          this.$confirm("当前产品名称存在重复，是否继续提交？", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",closeOnClickModal:false,
            type: "warning",
          }).then(function () {
            _this.submitData();
          });
        } else {
          this.submitData();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      const name = row.productName || this.selectNames;
      this.$confirm('是否确认删除产品名称为"' + name + '"的数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "warning",
      })
        .then(function () {
          return delProduct(productIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.btnLoading = true;
      this.download(
        "technology/technologyWorkingProduct/export",
        {
          ...this.queryParams,
        },
        `technology_product.xlsx`,
        "",
        () => {
          this.btnLoading = false;
        }
      );
    },
  },
};
</script>